import Youdao from "youdao-fanyi";
import axios from "axios";
import { v4 as uuidv4 } from "uuid";
import qs from "qs";

const streamToMp3 = (stream) => {};

const getInput = (input) => {
  if (input.length == 0) {
    return null;
  }
  var result;
  var len = input.length;
  if (len <= 20) {
    result = input;
  } else {
    var startStr = input.substring(0, 10);
    var endStr = input.substring(len - 10, len);
    result = startStr + len + endStr;
  }
  return result;
};

const createSign = (appKey, appSecret, query, salt) => {
  const curtime = Math.round(new Date().getTime() / 1000);
  const str = appKey + getInput(query) + salt + curtime + appSecret;
  // const sha256 = crypto.createHash("sha256");
  const sign = CryptoJS.SHA256(str).toString(CryptoJS.enc.Hex);
  return {
    sign,
    salt,
    appKey,
    curtime,
    signType: "v3",
  };
};

const truncate = (q) => {
  var len = q.length;
  if (len <= 20) return q;
  return q.substring(0, 10) + len + q.substring(len - 10, len);
};

const getTextMp3 = (text: string, lang: string) => {
  var appKey = "37f0b99a50c5487a";
  var key = "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3"; //注意：暴露appSecret，有被盗用造成损失的风险
  var salt = new Date().getTime();
  var curtime = Math.round(new Date().getTime() / 1000);
  var query = text;
  // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
  var from = "zh-CHS";
  var to = "en";
  var str1 = appKey + truncate(query) + salt + curtime + key;
  //console.log('---',str1);

  var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "https://openapi.youdao.com/api",
      type: "post",
      dataType: "jsonp",
      data: {
        q: query,
        appKey: appKey,
        salt: salt,
        from: from,
        to: to,
        sign: sign,
        signType: "v3",
        curtime: curtime,
        voiceName: "youxiaoqin",
      },
      success: function (data) {
        console.log(data);
        resolve(data);
      },
      error: function (err) {
        console.log(err);
        reject(err);
      },
    });
  });
};

const newGetTextMp4 = async (texts: string, lang: string) => {
  var appKey = "37f0b99a50c5487a";
  var key = "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3"; //注意：暴露appSecret，有被盗用造成损失的风险
  var salt = new Date().getTime();
  var curtime = Math.round(new Date().getTime() / 1000);
  var query = "week";
  // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
  var from = "zh-CHS";
  var to = "en";
  var str1 = appKey + truncate(query) + salt + curtime + key;
  //console.log('---',str1);

  var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

  let obj = {
    q: query,
    appKey: appKey,
    salt: salt,
    sign: sign,
    signType: "v3",
    curtime: curtime,
    voiceName: "youxiaoqin",
  };
  debugger;
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "https://openapi.youdao.com/ttsapi",
      type: "post",
      data: obj,
      success: function (data) {
        console.log(data);
        debugger;
        resolve(data);
      },
      error: function (err) {
        console.log(err);
        reject(err);
      },
    });
  });
};

const newGetTextMp3 = async (texts: string, lang: string) => {
  let data = new FormData();
  let appKey = "37f0b99a50c5487a";
  var secretKey = "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3";
  const { sign, salt, curtime, signType } = createSign(
    appKey,
    secretKey,
    texts
  );
  data.append("q", texts);
  data.append("appKey", appKey);
  data.append("salt", salt);
  data.append("sign", sign);
  data.append("signType", signType);
  data.append("curtime", curtime);
  data.append("format", "mp3");
  data.append("speed", "1");
  data.append("volume", "1");
  data.append("voiceName", "youxiaoqin");
  debugger;
  var config = {
    method: "post",
    url: "https://openapi.youdao.com/ttsapi",
    headers: { "content-type": "application/x-www-form-urlencoded" },
    query: data,
    data: data,
  };

  return new Promise((resolve, reject) => {
    axios(config)
      .then((response) => {
        const blob = new Blob([response.data], { type: "audio/mp3" });
        let url = window.URL.createObjectURL(blob);
        // 创建一个链接元素
        const a = document.createElement("a");
        a.href = url;
        a.download = "example.mp3"; // 设置下载的默认文件名

        // 模拟点击以触发下载
        document.body.appendChild(a); // 将链接添加到页面
        a.click(); // 模拟点击
        document.body.removeChild(a); // 下载后移除链接

        // 释放内存中的 URL
        window.URL.revokeObjectURL(url);

        debugger;

        resolve({ url });
      })
      .catch((error) => {
        console.log(error);
        reject(error);
      });
  });
};

const getTextMp5 = (text: string) => {
  var salt = uuidv4();
  var curtime = Math.round(new Date().getTime() / 1000);
  let appKey = "37f0b99a50c5487a";
  var secretKey = "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3";
  var str1 = appKey + truncate(text) + salt + curtime + secretKey;
  let sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
  let params: any = {
    q: text,
    voiceName: "youxiaohao",
    salt: salt,
    sign,
    appKey,
    langType: "zhiqi",
    speed: 1.2,
  };
  new Promise((resolve, reject) => {
    axios
      .get("https://openapi.youdao.com/ttsapi", { params })
      .then(function (response) {
        console.log(response);
        resolve(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  });
};
const getTextToSpeech = (text: string, lang: string) => {
  var data = JSON.stringify({
    text: "This is a test for the API of ElevenLabs.",
    model_id: "eleven_turbo_v2",
  });

  var config = {
    method: "post",
    url: "https://s.lconai.com/v1/text-to-speech/9BWtsMINqrJLrRacOk9x",
    headers: {
      Authorization: "sk-bBAVH84CrsNXb8FjUoUgCGyUzIs8aCGv0dWqGaUeSXUxXpiw",
      "Content-Type": "application/json",
    },
    data: data,
  };

  axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
      debugger;
    })
    .catch(function (error) {
      console.log(error);
    });
};

getTextToSpeech("", "");

function transformData(data) {
  let ret = "";
  for (let it in data) {
    ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
  }
  return ret;
}

const getTextMp6 = (text: string, lang: string) => {
  var appKey = "37f0b99a50c5487a";
  var key = "kZfwOflKNsAf9qmRyaxE4rBI4tnKuCK3"; //注意：暴露appSecret，有被盗用造成损失的风险
  var salt = new Date().getTime();
  var curtime = Math.round(new Date().getTime() / 1000);
  var query = text;
  // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
  var from = "zh-CHS";
  var to = "en";
  var str1 = appKey + truncate(query) + salt + curtime + key;
  //console.log('---',str1);

  var sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);
  return new Promise((resolve, reject) => {
    $.ajax({
      url: "https://openapi.youdao.com/ttsapi",
      type: "post",
      data: {
        q: query,
        appKey: appKey,
        salt: salt,
        from: from,
        to: to,
        sign: sign,
        signType: "v3",
        curtime: curtime,
        voiceName: "youxiaoqin",
      },
      success: function (data) {
        console.log(data);
        const blob = new Blob([data.data], { type: "audio/mp3" });
        let url = window.URL.createObjectURL(blob);
        debugger
        // 创建一个链接元素
        const a = document.createElement("a");
        a.href = url;
        a.download = "example.mp3"; // 设置下载的默认文件名

        // 模拟点击以触发下载
        document.body.appendChild(a); // 将链接添加到页面
        a.click(); // 模拟点击
        document.body.removeChild(a); // 下载后移除链接

        // 释放内存中的 URL
        window.URL.revokeObjectURL(url);
        resolve(data);
      },
      error: function (err) {
        debugger
        console.log(err);
        reject(err);
      },
    });
  });
};

export { getTextMp3, newGetTextMp3, newGetTextMp4, getTextMp5, getTextMp6 };
